<?php

/*
 * @author Ebrain Cedeno <ebraincedeno@gmail.com>
 */

class UserController extends Controller{
    
    
    public function actionLogin(){
        
        if (TSession::getStatusSession() == true){
            header("location:http://".$_SERVER['HTTP_HOST']."/index.php/home/menu");
            return false;
        }
        
        self::$theme_name = "Default_login";
        
        $user = new user();
        
        //si vamos a logearnos entramos aqui
        
        if (isset($_POST['entrar'])){
            
            $user->setAttributes($_POST);
            if ($user->login == ""){
                TForm::addMessageError("validate_login", "El campo usuario esta vacio por favor verifique"); 
            }
            else if ($user->password == ""){
                TForm::addMessageError("validate_login", "El campo clave esta vacio por favor verifique"); 
            }
            else if ($user->Count("login = :login AND password = :password",array(":login"=>$user->login,":password"=>md5($user->password))) == 0){
                TForm::addMessageError("validate_login", "Usuario o Clave Son Incorrectos por favor verifique");
            }
            else{
                
                $userData = user::model()->find("login = :login AND password = :password",array(":login"=>$user->login,":password"=>md5($user->password)));
                $obj_user = new stdClass();
                
                //generando los datos del usuario en la sesion
                
                foreach ($userData as $valor=>$objeto){
                    if (is_object($objeto)){
                        $obj_user->$valor = new stdClass();
                        foreach ($objeto as $key=>$value){
                            $obj_user->$valor->$key = $value;
                        }
                    }
                    else{
                        $obj_user->$valor = $objeto;
                    }
                }
                TSession::add("user", $obj_user);
                TSession::SessionActive();
                $this->redirec('../home/menu');
                
            }   
        }
        
        $this->form = new TForm();
        $this->form->Method = 'POST';
        $this->form->Action = VeCms::createUrl("./login");
        
        $this->user_label = new TLabel("Usuario:");
        $this->user_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->user_entry = new TEdit();
        $this->user_entry->Name = "login";
        $this->user_entry->Id = $this->user_entry->Name;
        $this->user_entry->Type = "text";
        $this->user_entry->Width = 250;
        $this->user_entry->Height = 25;
        $this->user_entry->Text = $user->login;
        $this->user_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        $this->passwd_label = new TLabel("Clave:");
        $this->passwd_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->passwd_entry = new TEdit();
        $this->passwd_entry->Width = 250;
        $this->passwd_entry->Height = 25;
        $this->passwd_entry->Name = "password";
        $this->passwd_entry->Id = $this->passwd_entry->Name;
        $this->passwd_entry->Type = "password";
        $this->passwd_entry->Text = $user->password;
        $this->passwd_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        $this->button_entrar = new TButton("Entrar");
        $this->button_entrar->Width = 75;
        $this->button_entrar->Name = "entrar";
        $this->button_entrar->OptionsAditional = array('style'=>array('font-weight:bold',
                                                                        'cursor:pointer',
                                                                        'border:1px solid gray',
                                                                        'background-image:url('.VeCms::getPathImage().'/login.png)',
                                                                        'background-position:left',
                                                                        'background-repeat: no-repeat',
                                                                        'background-position-x:5px',
                                                                        'text-align: right'));
        
        
    }
    
    
    public function actionNew(){
        
        VeCms::AccessValidate(array("admin"=>1));
        
        $user = new user();
        
        if(isset($_POST['guardar'])){
            
            $_POST['date_register'] = time();
            $_POST['date_last_connect'] = time();
            $user->setAttributes($_POST);
            $user->password = md5($user->password);
            if ($user->validate()){
                if ($user->save()){
                    TForm::addMessage("registrado", "El registro se realizo correctamente");
                    $this->redirec(VeCms::createUrl('./grid'),5);
                }
            }
        }
        
        $this->link_back = new TLink("Regresar");
        $js_link = "parent.history.back(); 
                    return false; 
                    ";
        $this->link_back->onClick = $js_link;
        $this->link_back->OptionsAditional['style'][] = "color:#A9BCF5";
        $this->link_back->OptionsAditional['style'][] = "font-weight:bold";
        
        
        $this->form = new TForm();
        $this->form->Method = 'POST';
        $this->form->Action = VeCms::createUrl('./new');

        $this->first_name_label = new TLabel("Nombre:");
        $this->first_name_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->first_name_entry = new TEdit();
        $this->first_name_entry->Name = "first_name";
        $this->first_name_entry->Id = $this->first_name_entry->Name;
        $this->first_name_entry->Width = 250;
        $this->first_name_entry->Height = 25;
        $this->first_name_entry->Type = 'text';
        $this->first_name_entry->Text = $user->first_name;
        $this->first_name_entry->OptionsAditional['style'] = array('border:1px solid black');

        $this->last_name_label = new TLabel("Apellido:");
        $this->last_name_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->last_name_entry = new TEdit();
        $this->last_name_entry->Name = "last_name";
        $this->last_name_entry->Id = $this->last_name_entry->Name;
        $this->last_name_entry->Width = 250;
        $this->last_name_entry->Height = 25;
        $this->last_name_entry->Type = 'text';
        $this->last_name_entry->Text = $user->last_name;
        $this->last_name_entry->OptionsAditional['style'] = array('border:1px solid black');

        $this->email_label = new TLabel("Correo:");
        $this->email_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->email_entry = new TEdit();
        $this->email_entry->Name = "e_mail";
        $this->email_entry->Id = $this->email_entry->Name;
        $this->email_entry->Width = 250;
        $this->email_entry->Height = 25;
        $this->email_entry->Type = 'text';
        $this->email_entry->Text = $user->e_mail;
        $this->email_entry->OptionsAditional['style'] = array('border:1px solid black');

        $this->phone_label = new TLabel("Telefono:");
        $this->phone_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->phone_entry = new TEdit();
        $this->phone_entry->Name = "phone";
        $this->phone_entry->Id = $this->phone_entry->Name;
        $this->phone_entry->Width = 250;
        $this->phone_entry->Height = 25;
        $this->phone_entry->Type = 'text';
        $this->phone_entry->Text = $user->phone;
        $this->phone_entry->OptionsAditional['style'] = array('border:1px solid black');
        
        $this->phone_mobile_label = new TLabel("Celular:");
        $this->phone_mobile_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->phone_mobile_entry = new TEdit();
        $this->phone_mobile_entry->Name = "phone_mobile";
        $this->phone_mobile_entry->Id = $this->phone_mobile_entry->Name;
        $this->phone_mobile_entry->Width = 250;
        $this->phone_mobile_entry->Height = 25;
        $this->phone_mobile_entry->Type = 'text';
        $this->phone_mobile_entry->Text = $user->phone_mobile;
        $this->phone_mobile_entry->OptionsAditional['style'] = array('border:1px solid black');
        
        $this->address_label = new TLabel("Direccion:");
        $this->address_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->address_textview = new TTextView();
        $this->address_textview->Name = "address";
        $this->address_textview->Id = $this->address_textview->Name;
        $this->address_textview->Cols = "10";
        $this->address_textview->Rows = "10";
        $this->address_textview->Width = 250;
        $this->address_textview->Height = 50;
        $this->address_textview->Text = $user->address;
        $this->address_textview->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        
        $this->user_label = new TLabel("Usuario:");
        $this->user_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->user_entry = new TEdit();
        $this->user_entry->Name = "login";
        $this->user_entry->Id = $this->user_entry->Name;
        $this->user_entry->Type = "text";
        $this->user_entry->Width = 250;
        $this->user_entry->Height = 25;
        $this->user_entry->Text = $user->login;
        $this->user_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        //clave
        
        $this->passwd_label = new TLabel("Clave:");
        $this->passwd_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->passwd_entry = new TEdit();
        $this->passwd_entry->Width = 250;
        $this->passwd_entry->Height = 25;
        $this->passwd_entry->Name = "password";
        $this->passwd_entry->Id = $this->passwd_entry->Name;
        $this->passwd_entry->Type = "password";
        $this->passwd_entry->Text = $user->password;
        $this->passwd_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        //rol
        
        $this->rol_label = new TLabel("Rol:");
        $this->rol_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->rol_entry = new TComboBox();
        $this->rol_entry->Name = "id_rol";
        $this->rol_entry->Id = $this->rol_entry->Name;
        $this->rol_entry->Width = 250;
        $this->rol_entry->Height = 25;
        $this->rol_entry->Type = 'text';
        $this->rol_entry->Selected = $user->id_rol;
        $this->rol_entry->OptionsAditional['style'] = array('border:1px solid black');
        
        //cargando los datos de los roles
        
        $roles = rol::model()->findAll("active=:active",array(":active"=>1));
        foreach ($roles as $key=>$value){
            $this->rol_entry->Options[]=array($value->id_rol,$value->description);
        }
        
        //buttons
        
        $this->button_reset = new TButton("Cancelar");
        $this->button_reset->Type = "reset";
        $this->button_reset->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));
        
        $this->button_entrar = new TButton("Guardar");
        $this->button_entrar->Name = "guardar";
        $this->button_entrar->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));

    }
    
    public function actionGrid(){
        
        // validamos el acceso
        
        VeCms::AccessValidate(array("admin"=>1));
        
        if (isset($_GET['del'])){
            $this->user_del = true;
            $this->validate = new TForm();
            
            TForm::addMessage('eliminado', "El usuario se elimino correctamente");
        }
        else{
            $this->user_del = false;
        }
        
        $this->button_new_user = new TButton("Nuevo Usuario");
        $this->button_new_user->Name = "new_user";
        
        $js_action_new_user = '
            $(location).attr("href","../user/new");
        ';
        
        $this->button_new_user->onClick = $js_action_new_user;
        $this->button_new_user->Type = "button";
        $this->button_new_user->Width = "130";
        $this->button_new_user->OptionsAditional = array('style'=>array('font-weight:bold',
                                                                        'cursor:pointer',
                                                                        'border:1px solid gray',
                                                                        'background-image:url('.VeCms::getPathImage().VeCmsEnum::ICON_ADD.')',
                                                                        'background-position:left',
                                                                        'background-repeat: no-repeat',
                                                                        'background-position-x:5px',
                                                                        'text-align: right'));
        
        //capturamos el offset para poner a funcionar el paginado
        
        $offset = (isset($_GET['offset']))?$_GET['offset']:0;
        
        $class_user = new user();
        $class_user->Limit = 10;
        $class_user->Offset = $offset;
        
        $user = $class_user->findAll("active=:active",array(":active"=>1));
        
        $this->grid_user = new TTable();
        $this->grid_user->Id = 'grid-user';
        $this->grid_user->Columns = 8;
        $this->grid_user->Rows = $class_user->Limit;
        $this->grid_user->Width = "100%";
        $this->grid_user->Headers = array('Nro','Nombre','Apellido','Telefono','Usuario','','','');
        $this->grid_user->WidthCell[0] = 25;
        $this->grid_user->WidthCell[5] = 25;
        $this->grid_user->WidthCell[6] = 25;
        $this->grid_user->WidthCell[7] = 25;
        $this->grid_user->RowsAlign[0] = 'center';

        $contador = 1;
        
        foreach($user as $key=>$value){
            
            // cargando el control para la vista previa de los datos del usuario
            
            $view = new TImage();
            $view->Src = VeCms::getPathImage().VeCmsEnum::ICON_VIEW;
            $view_js = '$(location).attr("href","../user/view?id_user='.$value->id_user.'");';
            $view->onClick = $view_js;
            $view->OptionsAditional['style'][] = 'cursor:pointer;';
            
            //cargamos el control para la edicion de los datos del usuario
            
            $edit = new TImage();
            $edit->Src = VeCms::getPathImage().VeCmsEnum::ICON_EDIT;
            $edit_js = '$(location).attr("href","../user/update?id_user='.$value->id_user.'");';
            $edit->onClick = $view_js = '$(location).attr("href","../user/update?id_user='.$value->id_user.'");';
            $edit->OptionsAditional['style'][] = 'cursor:pointer;';
            
            
            //cargamos el control para la eliminacion del usuario
            
            $delete = new TImage();
            $delete->Src = VeCms::getPathImage().VeCmsEnum::ICON_DELETE;
            
            $delete_js = 'if (confirm("Esta seguro que desea eliminar este usuario?")){
                                $(location).attr("href","../user/delete?id_user='.$value->id_user.'");
                          }';
            
            $delete->onClick = $delete_js;
            $delete->OptionsAditional['style'][] = 'cursor:pointer;';
            
            $this->grid_user->Items[] = array($contador,$value->first_name,$value->last_name,$value->phone,$value->login,$view->show(),$edit->show(),$delete->show()); 
            $contador++;
        }
        
        $this->grid_user->Pagination = new TPagination(array('offset'=>$offset,'limit'=>$class_user->Limit,'total'=>user::model()->Count("active=:active",array(":active"=>1))));    
    }
    
    public function actionView(){
        
        VeCms::AccessValidate(array("admin"=>1));
        
        $user = user::model()->find("id_user = :id_user",array(":id_user"=>$_GET['id_user']));
        
        $this->link_back = new TLink("Regresar");
        $js_link = "parent.history.back(); 
                    return false; 
                    ";
        $this->link_back->onClick = $js_link;
        $this->link_back->OptionsAditional['style'][] = "color:#A9BCF5";
        $this->link_back->OptionsAditional['style'][] = "font-weight:bold";
                
        //generamos los controles de la vista...
        
        $this->first_name_label = new TLabel("Nombres:");
        $this->first_name_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->first_name_value = new TLabel($user->first_name);
        
        $this->last_name_label = new TLabel("Apellidos:");
        $this->last_name_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->last_name_value = new TLabel($user->last_name);
        
        $this->id_rol_label = new TLabel("Rol:");
        $this->id_rol_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->id_rol_value = new TLabel($user->rol->description);
        
        $this->email_label = new TLabel("Correo:");
        $this->email_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->email_value = new TLabel($user->e_mail);
        
        $this->phone_label = new TLabel("Telefono:");
        $this->phone_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->phone_value = new TLabel($user->phone);
        
        $this->phone_mobile_label = new TLabel("Celular:");
        $this->phone_mobile_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->phone_mobile_value = new TLabel($user->phone_mobile);
        
        $this->address_label = new TLabel("Direccion:");
        $this->address_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->address_value = new TLabel($user->address);
        
        $this->login_label = new TLabel("Usuario:");
        $this->login_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->login_value = new TLabel($user->login);
        
        $this->date_register_label = new TLabel("Fecha de registro:");
        $this->date_register_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->date_register_value = new TLabel(date("d-m-Y",$user->date_register));
        
        $this->date_last_connect_label = new TLabel("Fecha ultima conexion:");
        $this->date_last_connect_label->OptionsAditional['style'][] = 'font-weight:bold';
        $this->date_last_connect_value = new TLabel(date("d-m-Y",$user->date_last_connect));
        
    }
    
    public function actionUpdate(){
        
        VeCms::AccessValidate(array("admin"=>1));
        
        $user = new user();
        
        if(isset($_POST['actualizar'])){
            $_POST['date_register'] = time();
            $_POST['date_last_connect'] = time();
            $user->setAttributes($_POST);
            $user->password = md5($user->password);
            if ($user->validate()){
                if ($user->update()){
                    TForm::addMessage("registrado", "El registro se actualizo correctamente");
                    $this->redirec(VeCms::createUrl('./grid'),5);
                }
            }
        }
        
        $class_user = $user->find("id_user = :id_user",array(":id_user"=>$_GET['id_user']));
        
        $this->link_back = new TLink("Regresar");
        $js_link = "parent.history.back(); 
                    return false; 
                    ";
        $this->link_back->onClick = $js_link;
        $this->link_back->OptionsAditional['style'][] = "color:#A9BCF5";
        $this->link_back->OptionsAditional['style'][] = "font-weight:bold";
        
        $this->form = new TForm();
        $this->form->Method = 'POST';
        $this->form->Action = VeCms::createUrl('./update?id_user='.$_GET['id_user']);

        $this->first_name_label = new TLabel("Nombre:");
        $this->first_name_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->first_name_entry = new TEdit();
        $this->first_name_entry->Name = "first_name";
        $this->first_name_entry->Id = $this->first_name_entry->Name;
        $this->first_name_entry->Width = 250;
        $this->first_name_entry->Height = 25;
        $this->first_name_entry->Type = 'text';
        $this->first_name_entry->Text = $class_user->first_name;
        $this->first_name_entry->OptionsAditional['style'] = array('border:1px solid black');

        $this->last_name_label = new TLabel("Apellido:");
        $this->last_name_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->last_name_entry = new TEdit();
        $this->last_name_entry->Name = "last_name";
        $this->last_name_entry->Id = $this->last_name_entry->Name;
        $this->last_name_entry->Width = 250;
        $this->last_name_entry->Height = 25;
        $this->last_name_entry->Type = 'text';
        $this->last_name_entry->Text = $class_user->last_name;
        $this->last_name_entry->OptionsAditional['style'] = array('border:1px solid black');

        $this->email_label = new TLabel("Correo:");
        $this->email_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->email_entry = new TEdit();
        $this->email_entry->Name = "e_mail";
        $this->email_entry->Id = $this->email_entry->Name;
        $this->email_entry->Width = 250;
        $this->email_entry->Height = 25;
        $this->email_entry->Type = 'text';
        $this->email_entry->Text = $class_user->e_mail;
        $this->email_entry->OptionsAditional['style'] = array('border:1px solid black');

        $this->phone_label = new TLabel("Telefono:");
        $this->phone_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->phone_entry = new TEdit();
        $this->phone_entry->Name = "phone";
        $this->phone_entry->Id = $this->phone_entry->Name;
        $this->phone_entry->Width = 250;
        $this->phone_entry->Height = 25;
        $this->phone_entry->Type = 'text';
        $this->phone_entry->Text = $class_user->phone;
        $this->phone_entry->OptionsAditional['style'] = array('border:1px solid black');
        
        $this->phone_mobile_label = new TLabel("Celular:");
        $this->phone_mobile_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->phone_mobile_entry = new TEdit();
        $this->phone_mobile_entry->Name = "phone_mobile";
        $this->phone_mobile_entry->Id = $this->phone_mobile_entry->Name;
        $this->phone_mobile_entry->Width = 250;
        $this->phone_mobile_entry->Height = 25;
        $this->phone_mobile_entry->Type = 'text';
        $this->phone_mobile_entry->Text = $class_user->phone_mobile;
        $this->phone_mobile_entry->OptionsAditional['style'] = array('border:1px solid black');
        
        $this->address_label = new TLabel("Direccion:");
        $this->address_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->address_textview = new TTextView();
        $this->address_textview->Name = "address";
        $this->address_textview->Id = $this->address_textview->Name;
        $this->address_textview->Cols = "10";
        $this->address_textview->Rows = "10";
        $this->address_textview->Width = 250;
        $this->address_textview->Height = 50;
        $this->address_textview->Text = $class_user->address;
        $this->address_textview->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        
        $this->user_label = new TLabel("Usuario:");
        $this->user_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->user_entry = new TEdit();
        $this->user_entry->Name = "login";
        $this->user_entry->Id = $this->user_entry->Name;
        $this->user_entry->Type = "text";
        $this->user_entry->Width = 250;
        $this->user_entry->Height = 25;
        $this->user_entry->Text = $class_user->login;
        $this->user_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        //clave
        
        $this->passwd_label = new TLabel("Clave:");
        $this->passwd_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->passwd_entry = new TEdit();
        $this->passwd_entry->Width = 250;
        $this->passwd_entry->Height = 25;
        $this->passwd_entry->Name = "password";
        $this->passwd_entry->Id = $this->passwd_entry->Name;
        $this->passwd_entry->Type = "password";
        $this->passwd_entry->Text = $class_user->password;
        $this->passwd_entry->OptionsAditional = array('style'=>array('border:1px solid black'));
        
        //rol
        
        $this->rol_label = new TLabel("Rol:");
        $this->rol_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->rol_entry = new TComboBox();
        $this->rol_entry->Name = "id_rol";
        $this->rol_entry->Id = $this->rol_entry->Name;
        $this->rol_entry->Width = 250;
        $this->rol_entry->Height = 25;
        $this->rol_entry->Type = 'text';
        $this->rol_entry->Selected = $class_user->id_rol;
        $this->rol_entry->OptionsAditional['style'] = array('border:1px solid black');
        
        //cargando los datos de los roles
        
        $roles = rol::model()->findAll("active=:active",array(":active"=>1));
        foreach ($roles as $key=>$value){
            $this->rol_entry->Options[]=array($value->id_rol,$value->description);
        }
        
        //hidden
        
        $this->id_user_entry = new TEdit();
        $this->id_user_entry->Name = "id_user";
        $this->id_user_entry->Id = $this->id_user_entry->Name;
        $this->id_user_entry->IsHidden = true;
        $this->id_user_entry->Text = $_GET['id_user'];
        
        //buttons
        
        $this->button_reset = new TButton("Cancelar");
        $this->button_reset->Type = "reset";
        $this->button_reset->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));
        
        $this->button_entrar = new TButton("Actualizar");
        $this->button_entrar->Name = "actualizar";
        $this->button_entrar->OptionsAditional = array('style'=>array('font-weight:bold','cursor:pointer'));

        
    }
    
    public function actionDelete(){
        
        VeCms::AccessValidate(array("admin"=>1));
        
        if (isset($_GET['id_user'])){
            
            $user = user::model()->find("id_user = :id_user",array(":id_user"=>$_GET['id_user']));
            $user->active = 0;
            if ($user->update()){
                $this->redirec('../home/menu',0,array("del"=>true));
            }
            else{
                throw new Exception("error al intentar eliminar el usuario de id ".$_GET['id_user']);
            }
            
        }
        else{
            throw new Exception("Error al intentar eliminar el usuario indicado");
        }
        
    }
    
    public function actionLogout(){
        
        TSession::Sessiondestroy();
        $this->redirec("../user/login");
        
    }
    
}
?>
